package net.hn.hnms.sys.common.satoken.config;

import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.domain.SysDept;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 智呈物联 pan'sx
 * 2022/11/29 9:51
 * 1.0 version
 */
@Aspect
@Component
public class SetContainOrgs {

    @Around(value = "@annotation(net.hn.hnms.sys.common.satoken.config.AutoSetContainOrgs)")
    public Object setMineCode(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        parameter:
        for (int i = 0; i < parameterNames.length; i++) {
            if (args[i] instanceof String[] || args[i] == null) {
                if ("containOrgs".equals(parameterNames[i])) {
                    if (args[i] == null || StringUtils.isBlank(args[i].toString())) {
                        LoginUser loginUser = LoginHelper.getLoginUser();
                        List<String> collect = loginUser.getContainOrgs().stream().map(SysDept::getOrganizationCode).collect(Collectors.toList());
                        args[i] = collect.toArray(new String[collect.size()]);
                        break parameter;
                    }
                }
            } else if (args[i] instanceof Object) {//接收参数是对象时适用
                Class classObj = (Class) args[i].getClass();
                if (!classObj.getPackage().getName().contains("net.hn")) continue;
                Field[] fields = classObj.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if ("containOrgs".equals(field.getName()) && field.getType() == String[].class && StringUtils.isBlank((String) field.get(args[i]))) {
                        LoginUser loginUser = LoginHelper.getLoginUser();
                            List<String> collect = loginUser.getContainOrgs().stream().map(SysDept::getOrganizationCode).collect(Collectors.toList());
                            field.set(args[i], collect.toArray(new String[collect.size()]));
                            break parameter;
                    }
                }
            }
        }
        return joinPoint.proceed(args);
    }
}
